package com.reptile.mes;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.common.util.DingDingUtils;
import com.common.util.RedisUtil;
import com.common.vo.dd.BaseLinkVo;
import com.common.vo.dd.DingDingFeedCardVo;
import com.google.common.collect.Lists;
import com.reptile.constant.YsReptileConstant;
import com.reptile.dto.NewsDTO;
import com.reptile.service.YsNewsService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 发送钉钉通知公共类
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class DingDingHelp {

    private final YsNewsService ysNewsService;

    @Resource
    private RedisUtil redisUtil;
    /**
     * 发送钉钉方法
     *
     * @param btcResult
     * @param mesType
     */
    public void sendData(List<NewsDTO> btcResult, String mesType) throws Exception {
        if (CollectionUtils.isEmpty(btcResult)) {
            return;
        }
        log.info("过滤前数据条数：{}", btcResult.size());
        btcResult = this.filtering(btcResult);
        log.info("过滤后的数据条数：{}", btcResult.size());
        DingDingFeedCardVo dingDingFeedCardVo = DingDingFeedCardVo.builder().build();
        dingDingFeedCardVo.setMsgType(mesType);
        List<BaseLinkVo> baseLinkVos = Lists.newArrayList();
        btcResult.forEach(item -> {
            BaseLinkVo baseLinkVo = BaseLinkVo.builder()
                    .title("-" + item.getTitle())
                    .picURL(getUrl())
                    .messageURL(item.getUrl())
                    .build();
            baseLinkVos.add(baseLinkVo);
        });

        dingDingFeedCardVo.setLinks(baseLinkVos);
        log.info("要发送的对象{}", dingDingFeedCardVo.getJSONObjectString());
        DingDingUtils.sendToDingDing(dingDingFeedCardVo.getJSONObjectString(), dingDingFeedCardVo.getMsgType());
        //保存到数据库
        ysNewsService.saveNewsToDb(btcResult);
    }

    /**
     * 数据去重
     *
     * @param data
     * @return
     */
    private List<NewsDTO> filtering(List<NewsDTO> data) {
        Set<NewsDTO> ysNewsSet = new HashSet<>(data);
        return new ArrayList<>(ysNewsSet);
    }

    /**
     * 获取redis中地址信息
     * @return
     */
    private String getUrl() {
        return redisUtil.spopItem(YsReptileConstant.PIC_REDIS_KEY, 1).get(0);
    }
}
